const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const helper = require('../../util/helper');
const stringUtils = require('../../core/util/StringUtils');
const assign = require("lodash/assign");
const keys = require("lodash/keys");
const values = require("lodash/values");

function insertScenario(ctx,scenario_name,pic_url,room_id, house_type_id, hashScenarioMap){
    return new Promise((resolve, reject) => {
        let newscenario = {
            scenario_name,
            pic_url,
            room_id,
            house_type_id,
            is_deleted: 0,
            create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            update_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        };

        var trans = mysql.Client.startTransaction();
        trans.query(`INSERT INTO scenario SET ?`, newscenario, function(err, info) {
            if(err){
                trans.rollback();
                ctx.body = {
                    result: 202,
                    message: "新增场景失败"+ err.toString()
                };
                resolve(ctx);
            } else{
                let sqlInsertScenario_V_Device = `INSERT INTO t_scenario_v_device (scenario_id,v_device_id,property_name,value,property_values,type) VALUES  `;
                hashScenarioMap.forEach(ele => {
                    sqlInsertScenario_V_Device += `(${info.insertId }, ${ele.v_device_id},'${ele.property_name}','${ele.value}', '${ele.property_values}', '${ele.type}' ),`;
                })
                sqlInsertScenario_V_Device = sqlInsertScenario_V_Device.substr(0,sqlInsertScenario_V_Device.length-1);
                trans.query(sqlInsertScenario_V_Device, function(err) {
                    if(err){
                        trans.rollback();
                        ctx.body = {
                            result: 209,
                            message: "新增场景失败"+ err.toString()
                        };
                    } else{
                        trans.commit();
                        ctx.body = {
                            result: 200,
                            id: info.insertId,
                            message: "新增场景成功"
                        };
                    }
                    resolve(ctx);
                });
            }
        });
        trans.execute();
    });
};

function updateScenario(ctx,scenario_id, scenario_name,pic_url,room_id, house_type_id, hashScenarioMap){
    return new Promise((resolve, reject) => {
        let newscenario = {
            scenario_id,
            scenario_name,
            pic_url,
            room_id,
            house_type_id,
            is_deleted: 0,
            update_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        };

        var trans = mysql.Client.startTransaction();
        trans.query(`UPDATE scenario SET ? where scenario_id = ${scenario_id}`, newscenario, function(err, info) {
            if(err || info.affectedRows === 0){
                trans.rollback();
                ctx.body = {
                    result: 202,
                    message: "更新场景失败"+ err.toString()
                };
                resolve(ctx);
            } else{
                trans.query(`delete from t_scenario_v_device where scenario_id = ${scenario_id}`, function(err) {
                    if(err){
                        trans.rollback();
                        ctx.body = {
                            result: 209,
                            message: "更新场景失败"+ err.toString()
                        };
                        resolve(ctx);
                    } else{
                        let sqlInsertScenario_V_Device = `INSERT INTO t_scenario_v_device (scenario_id,v_device_id,property_name,value,property_values,type) VALUES  `;
                        hashScenarioMap.forEach(ele => {
                            sqlInsertScenario_V_Device += `(${scenario_id}, ${ele.v_device_id},'${ele.property_name}','${ele.value}', '${ele.property_values}', '${ele.type}' ),`;
                        })
                        sqlInsertScenario_V_Device = sqlInsertScenario_V_Device.substr(0,sqlInsertScenario_V_Device.length-1);
                        trans.query(sqlInsertScenario_V_Device, function(err) {
                            if(err){
                                trans.rollback();
                                ctx.body = {
                                    result: 209,
                                    message: "更新场景失败"+ err.toString()
                                };
                            }else{
                                trans.commit();
                                ctx.body = {
                                    result: 200,
                                    id: info.insertId,
                                    message: "更新场景成功"
                                };
                            }
                            resolve(ctx);
                        });
                    }
                });
            }
        });
        trans.execute();
    });
};


exports.add = async(ctx) => {
    let scenario_name = ctx.request.body.scenario_name ? ctx.request.body.scenario_name.trim() : '';
    let pic_url = ctx.request.body.pic_url || '';
    let house_type_id = ctx.request.body.house_type_id || 0;
    let room_id = ctx.request.body.room_id || 0;
    let matching_condition = ctx.request.body.matching_condition ? JSON.parse(ctx.request.body.matching_condition.replace(/\'/g,'\"')) : [];
    let triggering_condition = ctx.request.body.triggering_condition ? JSON.parse(ctx.request.body.triggering_condition.replace(/\'/g,'\"')) : [];
    let action = ctx.request.body.action ? JSON.parse(ctx.request.body.action.replace(/\'/g,'\"')) : [];

    try{
        if (scenario_name === '' || parseInt(house_type_id) <= 0 || parseInt(room_id) < 0 ) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        if (!Array.isArray(matching_condition) || !Array.isArray(triggering_condition) || !Array.isArray(action)) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        if (action.length === 0){
            ctx.body = {
                result: 202,
                message: "场景执行任务不能为空"
            };
            return;
        }
        let selectExistScenarios = await mysql.query(`select * from scenario where house_type_id = ? and scenario_name = ? and is_deleted = 0 `,[house_type_id,scenario_name]);
        if (selectExistScenarios.length > 0 ){
            ctx.body = {
                result: 203,
                message: "此户型已有重名场景"
            };
            return;
        }
        let hashScenarioMap = [];
        if (triggering_condition.length > 0) {
            triggering_condition.forEach((ele, index) => {
                let obj2 = {v_device_id:  ele.v_device_id, property_name:  ele.property_name, value:  ele.value, property_values: JSON.stringify(ele.properties), type: 0}
                hashScenarioMap.push(obj2);
            })
        }
        if (matching_condition.length > 0) {
            matching_condition.forEach((ele, index) => {
                let obj = {v_device_id:  ele.v_device_id, property_name:  ele.property_name, value:  ele.value, property_values: JSON.stringify(ele.properties), type: 1 }
                hashScenarioMap.push(obj);
            })
        }
        if (action.length > 0) {
            action.forEach((ele, index) => {
                let obj3 = {v_device_id:  ele.v_device_id, property_name:  ele.property_name, value:  ele.value, property_values: JSON.stringify(ele.properties), type: 2 }
                hashScenarioMap.push(obj3);
            })

        }

        await insertScenario(ctx,scenario_name,pic_url,room_id, house_type_id,hashScenarioMap);

    }catch (e) {
        ctx.body = {
            result: 205,
            message: "新增场景失败"+e.toString()
        };
    }
}

exports.delete = async(ctx) => {
    let scenario_id = ctx.params.scenario_id || 0;

    try{
        if (parseInt(scenario_id) <= 0) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return
        }
        ret = await mysql.query(`UPDATE scenario SET is_deleted = ? ,update_time = ? WHERE scenario_id = ${scenario_id} `, [1,moment().format('YYYY-MM-DD HH:mm:ss')]);
        if (ret.affectedRows <= 0){
            ctx.body = {
                result: 202,
                message: "删除失败"
            }
        } else{
            ctx.body = {
                result: 200,
                message: "删除成功"
            }
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let scenario_id = ctx.request.body.scenario_id || 0;
    let scenario_name = ctx.request.body.scenario_name ? ctx.request.body.scenario_name.trim() : '';
    let pic_url = ctx.request.body.pic_url || '';
    let house_type_id = ctx.request.body.house_type_id || 0;
    let room_id = ctx.request.body.room_id || 0;
    let matching_condition = ctx.request.body.matching_condition ? JSON.parse(ctx.request.body.matching_condition.replace(/\'/g,'\"')) : [];
    let triggering_condition = ctx.request.body.triggering_condition ? JSON.parse(ctx.request.body.triggering_condition.replace(/\'/g,'\"')) : [];
    let action = ctx.request.body.action ? JSON.parse(ctx.request.body.action.replace(/\'/g,'\"')) : [];

    try{
        if (parseInt(scenario_id) <= 0 || scenario_name === '' || parseInt(house_type_id) <= 0 || parseInt(room_id) < 0 ) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        if (!Array.isArray(matching_condition) || !Array.isArray(triggering_condition) || !Array.isArray(action)) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        if (action.length === 0){
            ctx.body = {
                result: 202,
                message: "场景执行任务不能为空"
            };
            return;
        }
        let selectExistScenarios = await mysql.query(`select * from scenario where house_type_id = ? and scenario_name = ? and is_deleted = 0 and scenario_id <> ? `
            ,[house_type_id,scenario_name,scenario_id]);
        if (selectExistScenarios.length > 0){
            ctx.body = {
                result: 203,
                message: "此户型已有重名场景"
            };
            return;
        }
        let hashScenarioMap = [];
        if (triggering_condition.length > 0) {
            triggering_condition.forEach((ele, index) => {
                let obj2 = {v_device_id:  ele.v_device_id, property_name:  ele.property_name, value:  ele.value, property_values: JSON.stringify(ele.properties), type: 0}
                hashScenarioMap.push(obj2);
            })
        }
        if (matching_condition.length > 0) {
            matching_condition.forEach((ele, index) => {
                let obj = {v_device_id:  ele.v_device_id, property_name:  ele.property_name, value:  ele.value, property_values: JSON.stringify(ele.properties), type: 1 }
                hashScenarioMap.push(obj);
            })

        }
        if (action.length > 0) {
            action.forEach((ele, index) => {
                let obj3 = {v_device_id:  ele.v_device_id, property_name:  ele.property_name, value:  ele.value, property_values: JSON.stringify(ele.properties), type: 2 }
                hashScenarioMap.push(obj3);
            })

        }

        await updateScenario(ctx,scenario_id,scenario_name,pic_url,room_id, house_type_id,hashScenarioMap);

        // ret = mysql.Client.query('SELECT * FROM building');
        // console.log('ret:',ret)
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "更新场景失败"+e.toString()
        };
    }

}

exports.getList = async(ctx) => {
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;
    let house_type_id = ctx.query.house_type_id || 0;
    let room_id = ctx.query.room_id || 0;

    try {
        if (parseInt(house_type_id) <= 0 || parseInt(room_id) < 0) {
            ctx.body = {
                result: 201,
                message: '请检查参数'
            };
            return;
        }
        let resultScenarios = (ctx.query.room_id !== undefined) ?
            await mysql.query(`SELECT * FROM scenario WHERE house_type_id = ${house_type_id} and room_id = ${room_id} and is_deleted = 0 ORDER BY scenario_id DESC LIMIT ${indexfrom}, ${counts} ` )
            : await mysql.query(`SELECT * FROM scenario WHERE house_type_id = ${house_type_id} and is_deleted = 0 ORDER BY scenario_id DESC LIMIT ${indexfrom}, ${counts} ` ) ;
        if (resultScenarios.affectedRows === 0){
            ctx.body = {
                result: 200,
                list:resultScenarios,
                totalpage:0,
                totalcounts:0,
                message: "查询成功"
            };
        } else{
            let totalResult = (ctx.query.room_id !== undefined) ?
                await mysql.query(`SELECT COUNT(scenario_id) AS total FROM scenario WHERE house_type_id = ${house_type_id} and room_id = ${room_id} and is_deleted = 0 `)
                : await mysql.query(`SELECT COUNT(scenario_id) AS total FROM scenario WHERE house_type_id = ${house_type_id} and is_deleted = 0 `);
            for (let scenario of Object.values(resultScenarios)) {
                let scenarioDevices = await mysql.query(`SELECT * FROM t_scenario_v_device WHERE scenario_id = ${scenario.scenario_id} ` );
                scenario.triggering_condition = [];
                scenario.matching_condition = [];
                scenario.action = [];
                for (let scenarioDevice of Object.values(scenarioDevices)) {
                    if (scenarioDevice.type === 0){
                        scenario.triggering_condition.push(scenarioDevice);
                    } else if(scenarioDevice.type === 1){
                        scenario.matching_condition.push(scenarioDevice);
                    }else{
                        scenario.action.push(scenarioDevice);
                    }
                }
            }
            ctx.body = {
                result: 200,
                list:resultScenarios,
                totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
                totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
                message: "查询成功"
            };
        }

    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.getDetail = async(ctx) => {
    let scenario_id = ctx.params.scenario_id || 0;

    try {
        if (parseInt(scenario_id) <= 0){
            ctx.body = {
                result: 201,
                message: '请检查参数'
            };
            return;
        }
        let resultScenarios = await mysql.query(`SELECT * FROM scenario WHERE scenario_id = ${scenario_id} and is_deleted = 0 ` ) ;
        if (resultScenarios.length === 0){
            ctx.body = {
                result: 201,
                message: "对象不存在或已删除"
            };
        }else{
            let scenarioDevices = await mysql.query(`SELECT * FROM t_scenario_v_device WHERE scenario_id = ${scenario_id} ` );
            resultScenarios[0].triggering_condition = [];
            resultScenarios[0].matching_condition = [];
            resultScenarios[0].action = [];
            for (let scenarioDevice of Object.values(scenarioDevices)) {
                if (scenarioDevice.type === 0){
                    resultScenarios[0].triggering_condition.push(scenarioDevice);
                } else if(scenarioDevice.type === 1){
                    resultScenarios[0].matching_condition.push(scenarioDevice);
                }else{
                    resultScenarios[0].action.push(scenarioDevice);
                }
            }
            ctx.body = {
                result: 200,
                resultInfo:resultScenarios[0],
                message: "查询成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}